from django.core.paginator import Paginator
from rest_framework.views import APIView
from .permissions import IsSuperUser
from .exceptions import JsonAPIException
from .authentication import AdmJSONWebTokenAuthentication
from . import ErrCode
from django.apps import apps
from .settings import adm_settings

class BaseAdmAPIView(APIView):
    """Base Adm API View"""
    resp = {}
    authentication_classes = (AdmJSONWebTokenAuthentication, )
    permission_classes = (IsSuperUser,)

    exclude_apps = adm_settings.EXCLUDE_APPS
    only_apps = adm_settings.ONLY_APPS

    def get_model(self, request, *args, **kwargs):
        app_name = kwargs.get('app_name')
        model_name = kwargs.get('model_name')
        try:
            model_object = apps.all_models[app_name][model_name]
        except KeyError:
            raise JsonAPIException(code=ErrCode.PARAM_ERROR.name, msg='请求的资源不存在', status=404)
        return model_object

    def permission_denied(self, request, message=None):
        """
        If request is not permitted, determine what kind of exception to raise.
        """
        if request.authenticators and not request.successful_authenticator:
            raise JsonAPIException(code=ErrCode.AUTH_FAILED.name, msg='不允许匿名访问', status=401)
        raise JsonAPIException(code=ErrCode.AUTH_FAILED.name, msg='权限拒绝', status=403)

    def page_objects(self, request, objects, page=None, size=None):
        if page and size:
            page = int(page)
            size = int(size)
        else:
            try:
                page = int(request.GET.get('page'))
                size = int(request.GET.get('size'))
            except:
                page = 1
                size = 15

        p = Paginator(objects, size, allow_empty_first_page=True)
        return p.count, p.page(page).object_list

